<?php
namespace apps\admin\controllers;

use enums\DBEnums;
use apps\admin\ext\AdminBaseController;
use Phalcon\Paginator\Adapter\QueryBuilder;
use apps\admin\models\SelectCategory;
use helpers\TimeUtils;
use apps\admin\models\SelectDic;
use apps\admin\enums\DisplayEnums;

/**
 * @comment( comment = '选项类别配置' )
 * 
 * @author ( author = 'bruce' )
 *         @date ( date = '2015-8-28' )
 */
class SelController extends AdminBaseController
{

    public function initialize()
    {
        parent::initialize();
        //$this->checkPlatform();
    }

    /**
     *
     * @author ( author='bruce' )
     *         @date( date = '2016年8月18日' )
     *         @comment( comment = '配置分类' )
     * @method ( method = 'categoryAction' )
     *         @op( op = '' )
     */
    public function indexCateAction()
    {
        $pageNum = $this->request->getQuery( 'page', 'int' );
        $currentPage = $pageNum ? $pageNum : 1;
        
        $builder = $this->modelsManager->createBuilder()
            ->from( 'apps\admin\models\SelectCategory' )
            ->where( 'delsign=' . DBEnums::DELSIGN_NO . ' ORDER BY sort ASC,uptime DESC' );
        
        $paginator = new QueryBuilder( array(
            'builder' => $builder,
            'limit' => DisplayEnums::PER_PAGE_LIST_NUM,
            'page' => $currentPage
        ) );
        $page = $paginator->getPaginate();
        $this->view->page = $page;
    }

    /**
     *
     * @author ( author='bruce' )
     *         @date( date = '2016年10月26日' )
     *         @comment( comment = '检测en_name是否重复' )
     * @method ( method = 'checkEnnameAction' )
     *         @op( op = '' )
     */
    public function checkEnnameAction()
    {
        try
        {
            $enname = $this->dispatcher->getParam( 'en_name', 'trim' );
            
            $objRet = new \stdClass();
            
            if( ! $enname || $enname == '' )
            {
                $objRet->status = 1;
                $objRet->msg = '英文名不能为空';
                
                echo json_encode( $objRet );
                return;
            }
            
            $where = array(
                'conditions' => 'en_name=:enname: and delsign=:del:',
                'bind' => array(
                    'enname' => $enname,
                    'del' => DBEnums::DELSIGN_NO
                )
            );
            
            $objCate = SelectCategory::findFirst( $where );
            
            if( $objCate !== false )
            {
                $objRet->status = 2;
                $objRet->msg = '英文名必须保持唯一';
            }
            else
            {
                $objRet->status = 0;
                $objRet->msg = '检测通过';
            }
            
            echo json_encode( $objRet );
        }
        catch (\Exception $e)
        {
            echo $e->getMessage();
        }
    }

    /**
     *
     * @author ( author='bruce' )
     *         @date( date = '2016年8月18日' )
     *         @comment( comment = '添加分类' )
     * @method ( method = 'addcateAction' )
     *         @op( op = '' )
     */
    public function addcateAction()
    {}

    /**
     *
     * @author ( author='bruce' )
     *         @date( date = '2016年8月18日' )
     *         @comment( comment = '编辑分类' )
     * @method ( method = 'editcateAction' )
     *         @op( op = '' )
     */
    public function editcateAction()
    {
        $catid = $this->dispatcher->getParam( 'id', 'int' );
        if( ! $catid )
            return $this->response->redirect( '/admin/sel/addcate' );
        
        $where = array(
            'columns' => 'id,title,sort,descr,en_name,getter,getter_descr,is_enum',
            'conditions' => 'id=:id: and delsign=:del:',
            'bind' => array(
                'id' => $catid,
                'del' => DBEnums::DELSIGN_NO
            )
        );
        $res = SelectCategory::findFirst( $where );
        
        if( $res && count( $res ) > 0 )
        {
            $this->view->res = $res;
            $this->view->pick( 'sel/addcate' );
        }
        else
            return $this->response->redirect( '/admin/sel/addcate' );
    }

    /**
     * 生成getter和常量
     *
     * @return boolean
     */
    public function generateGetterAndEnumsAction()
    {
        $iID = $this->dispatcher->getParam( 'id', 'int' );
        
        try
        {
            $cateWhere = array(
                'columns' => 'id,title,en_name,getter,getter_descr',
                'conditions' => 'delsign=?0 and id=?1',
                'bind' => array(
                    DBEnums::DELSIGN_NO,
                    $iID
                )
            );
            $objCate = SelectCategory::findFirst( $cateWhere );
            if( ! $objCate )
            {
                $objRet = new \stdClass();
                
                $objRet->status = 1;
                $objRet->msg = '未找到指定的记录';
                
                echo json_encode( $objRet );
                return;
            }
            
            $enumsWhere = array(
                'columns' => 'id,title,key,value',
                'conditions' => 'delsign=?0 and cateid=?1',
                'bind' => array(
                    DBEnums::DELSIGN_NO,
                    $iID
                ),
                'order' => 'sort asc'
            );
            $objEnums = SelectDic::find( $enumsWhere );
            if( ! $objEnums || ($iEnumsCount = count( $objEnums )) <= 0 )
            {
                $objRet = new \stdClass();
                
                $objRet->status = 1;
                $objRet->msg = '未找到指定的记录';
                
                echo json_encode( $objRet );
                return;
            }
            
            $strGetterName = $objCate->getter;
            $strGetterDescr = $objCate->getter_descr;
            
            $selPath = APP_ROOT . 'enums/SelectEnums.php';
            
            $strSelContent = file_get_contents( $selPath );
            $iLastBrace = strrpos( $strSelContent, '}' );
            $strSelContent = substr( $strSelContent, 0, $iLastBrace );
            
            $strGetterHeader = <<<GETTER
/**
	 * $strGetterDescr
	 */    	
	public static function $strGetterName()
	{
		return array(
GETTER;
            
            $strGetterFooter = <<<GETTER
	    	
		);
    }
GETTER;
            
            $bChangeContent = false;
            $strGetterContent = '';
            // 生成常量
            foreach( $objEnums as $enum )
            {
                $strConst = "SEL_" . strtoupper( $objCate->en_name ) . "_" . strtoupper( $enum->key );
                $strEnum = <<<ENUMS
   
	/**
	 *	$enum->title
	 */
	const $strConst = $enum->value;

	
ENUMS;
                
                if( false === strpos( $strSelContent, $strConst ) )
                { // 不存在则生成常量
                    $strSelContent = $strSelContent . $strEnum;
                    $bChangeContent = true;
                }
                
                if( false === strpos( $strSelContent, $objCate->getter ) )
                { // 不存在则生成getter
                    $strItem = <<<GETTER
		  
		    			self::$strConst => array( 'value' => $enum->value, 'title' => '$enum->title'),
GETTER;
                    $bChangeContent = true;
                    
                    $strGetterContent .= $strItem;
                }
            }
            
            if( $strGetterContent != '' )
            {
                $strSelContent .= $strGetterHeader . $strGetterContent . $strGetterFooter;
            }
            
            if( $bChangeContent )
            {
                file_put_contents( $selPath, $strSelContent . PHP_EOL . '}' );
            }
            
            $objRet = new \stdClass();
            
            $objRet->status = 0;
            $objRet->msg = '成功生成常量和访问器';
            
            echo json_encode( $objRet );
            // echo $strSelContent . PHP_EOL . '}';
        }
        catch (\Exception $e)
        {
            $objRet = new \stdClass();
            
            $objRet->status = 1;
            $objRet->msg = $e->getMessage();
            
            echo json_encode( $objRet );
        }
        
        $this->view->disable();
    }

    /**
     *
     * @author ( author='bruce' )
     *         @date( date = '2016年8月18日' )
     *         @comment( comment = '保存配置分类信息' )
     * @method ( method = 'saveCateAction' )
     *         @op( op = 'u' )
     */
    public function saveCateAction()
    {
        try
        {
            $selID = $this->request->getPost( 'id', 'int' );
            $title = $this->request->getPost( 'title', 'trim' );
            $descr = $this->request->getPost( 'descr', 'trim' );
            $sort = $this->request->getPost( 'sort', 'int' );
            $en_name = $this->request->getPost( 'en_name', 'trim' );
            $is_enum = $this->request->getPost( 'isenum', 'int' );
            $getter = $this->request->getPost( 'getter', 'trim' );
            $getter_descr = $this->request->getPost( 'getter_descr', 'trim' );
            
            if( ! $selID )
            {
                $category = new SelectCategory();
                $category->addtime = $category->uptime = TimeUtils::getFullTime();
                $category->delsign = DBEnums::DELSIGN_NO;
                $category->sort = $sort;
                $category->title = $title;
                $category->descr = $descr;
                $category->en_name = $en_name;
                $category->getter = $getter;
                $category->is_enum = $is_enum;
                $category->getter_descr = $getter_descr;
                
                if( $category->save() )
                {
                    return $this->response->redirect( '/admin/sel/indexCate' );
                }
                else
                {
                    return $this->response->redirect( '/admin/sel/addcate' );
                }
            }
            else
            {
                $where = array(
                    'conditions' => 'id=:id: and delsign=:del:',
                    'bind' => array(
                        'id' => $selID,
                        'del' => DBEnums::DELSIGN_NO
                    )
                );
                $category = SelectCategory::findFirst( $where );
                if( $category )
                {
                    $category->uptime = TimeUtils::getFullTime();
                    $category->sort = $sort;
                    $category->title = $title;
                    $category->descr = $descr;
                    $category->en_name = $en_name;
                    $category->getter = $getter;
                    $category->is_enum = $is_enum;
                    $category->getter_descr = $getter_descr;
                    
                    if( $category->save() )
                    {
                        return $this->response->redirect( '/admin/sel/indexCate' );
                    }
                    else
                    {
                        return $this->response->redirect( '/admin/sel/editcate/id/' . $selID );
                    }
                }
                else
                    return $this->response->redirect( '/admin/sel/catrgory' );
            }
        }
        catch (\Exception $e)
        {
            echo $e->getMessage();
        }
    }

    /**
     *
     * @author ( author='bruce' )
     *         @date( date = '2016年8月18日' )
     *         @comment( comment = '系统配置中心' )
     * @method ( method = 'indexAction' )
     *         @op( op = '' )
     */
    public function indexSelAction()
    {
        $catId = $this->request->getQuery( 'cateid', 'int' );
        $pageNum = $this->request->getQuery( 'page', 'int' );
        $currentPage = $pageNum ? $pageNum : 1;
        
        $where = 'a.delsign=' . DBEnums::DELSIGN_NO . ' ORDER BY a.uptime desc, c.sort ASC';
        if( $catId && false != $catId )
            $where = 'a.delsign=' . DBEnums::DELSIGN_NO . ' AND a.cateid=' . $catId . ' ORDER BY a.uptime desc, c.sort ASC';
        
        $builder = $this->modelsManager->createBuilder()
            ->columns( 'a.id,a.key,a.value,a.valtype,a.title,a.sort,a.uptime,c.title as cat_title,c.en_name' )
            ->addFrom( 'apps\admin\models\SelectDic', 'a' )
            ->join( 'apps\admin\models\SelectCategory', 'a.cateid = c.id', 'c' )
            ->where( $where );
        
        $paginator = new QueryBuilder( array(
            'builder' => $builder,
            'limit' => 15,
            'page' => $currentPage
        ) );
        
        try
        {
            $page = $paginator->getPaginate();
            
            $this->view->page = $page;
        }
        catch (\Exception $e)
        {
            $this->errLog->error( $this->appVer['appVersion'] . '|' . $this->router->getModuleName() . '|' . __METHOD__ . '|系统配置中心:' . $e->getMessage() );
            return false;
        }
        
        $this->view->cateId = $catId ? $catId : 0;
        
        $category = SelectCategory::getAll();
        $this->view->category = $category;
    }

    /**
     *
     * @author ( author='bruce' )
     *         @date( date = '2016年8月18日' )
     *         @comment( comment = '添加配置项' )
     * @method ( method = 'addAction' )
     *         @op( op = '' )
     */
    public function addselAction()
    {
        $category = SelectCategory::getAll();
        
        $this->view->category = $category;
    }

    /**
     *
     * @author ( author='bruce' )
     *         @date( date = '2016年8月18日' )
     *         @comment( comment = '编辑配置项' )
     * @method ( method = 'editAction' )
     *         @op( op = '' )
     */
    public function editSelAction()
    {
        $id = $this->dispatcher->getParam( 'id', 'int' );
        if( ! $id )
            return $this->response->redirect( '/admin/sel/indexSel' );
        
        $where = array(
            'columns' => 'id,title,key,value,valtype,cateid,descr,sort',
            'conditions' => 'id=:id: and delsign=:del:',
            'bind' => array(
                'id' => $id,
                'del' => DBEnums::DELSIGN_NO
            )
        );
        $res = SelectDic::findFirst( $where );
        if( $res )
        {
            $category = SelectCategory::getAll();
            $this->view->category = $category;
            $this->view->res = $res;
            
            $this->view->pick( 'sel/addSel' );
        }
        else
            return $this->response->redirect( '/admin/sel/addSel' );
    }

    /**
     *
     * @author ( author='bruce' )
     *         @date( date = '2016年8月18日' )
     *         @comment( comment = '保存配置项信息' )
     * @method ( method = 'saveAction' )
     *         @op( op = '' )
     */
    public function saveSelAction()
    {
        $title = $this->request->getPost( 'title', 'trim' );
        $cateid = $this->request->getPost( 'cateid', 'int' );
        $key = $this->request->getPost( 'key', 'trim' );
        $valtype = $this->request->getPost( 'valtype', 'int' );
        $value = $this->request->getPost( 'value', 'trim' );
        $descr = $this->request->getPost( 'descr', 'trim' );
        $selID = $this->request->getPost( 'id', 'int' );
        $sort = $this->request->getPost( 'sort', 'int' );
        
        if( ! $selID )
        {
            $res = new SelectDic();
            $res->addtime = $res->uptime = TimeUtils::getFullTime();
            $res->delsign = DBEnums::DELSIGN_NO;
            $res->descr = $descr;
            $res->title = $title;
            $res->key = $key;
            $res->value = $value;
            $res->valtype = $valtype;
            $res->cateid = $cateid;
            $res->sort = $sort;
            
            if( $res->save() )
            {
                $objRet = new \stdClass();
                $objRet->status = 0;
                $objRet->url = '/admin/sel/indexSel';
                // return $this->response->redirect( );
            }
            else
            {
                $objRet = new \stdClass();
                $objRet->status = 1;
                $objRet->msg = '保存出错，请与管理员联系解决！';
                // return $this->response->redirect( '/admin/sel/addSel' );
            }
        }
        else
        {
            $where = array(
                'conditions' => 'id=:id: and delsign=:del:',
                'bind' => array(
                    'id' => $selID,
                    'del' => DBEnums::DELSIGN_NO
                )
            );
            $res = SelectDic::findFirst( $where );
            if( $res )
            {
                $res->uptime = TimeUtils::getFullTime();
                $res->descr = $descr;
                $res->title = $title;
                $res->key = $key;
                $res->value = $value;
                $res->valtype = $valtype;
                $res->cateid = $cateid;
                $res->sort = $sort;
                
                if( $res->save() )
                {
                    $objRet = new \stdClass();
                    $objRet->status = 0;
                    $objRet->url = '/admin/sel/indexSel';
                    // return $this->response->redirect( '/admin/sel/indexSel' );
                }
                else
                {
                    $objRet = new \stdClass();
                    $objRet->status = 1;
                    $objRet->msg = '保存出错，请与管理员联系解决！';
                    // return $this->response->redirect( '/admin/sel/addSel' );
                    // return $this->response->redirect( '/admin/sel/editSel/id/' . $selID );
                }
            }
            else
            {
                $objRet = new \stdClass();
                $objRet->status = 0;
                $objRet->url = '/admin/sel/indexSel';
                // return $this->response->redirect( '/admin/sel/indexSel' );
            }
        }
        
        echo json_encode( $objRet );
    }

    /**
     *
     * @author ( author='bruce' )
     *         @date( date = '2016年8月22日' )
     *         @comment( comment = '获取关键字 判断是否重复' )
     * @method ( method = 'getkeyAction' )
     *         @op( op = '' )
     */
    public function getSelkeyAction()
    {
        $iCateID = $this->dispatcher->getParam( 'cateid', 'int' );
        $key = $this->dispatcher->getParam( 'key', 'trim' );
        $objRet = new \stdClass();
        if( false === $key || $iCateID === false )
        {
            $objRet->status = 1;
            $objRet->msg = '参数错误,请刷新后再试..';
            
            echo json_encode( $objRet );
            return;
        }
        
        $where = array(
            'columns' => 'id,key',
            'conditions' => 'key=:key: and cateid = :cateid: and delsign=:del:',
            'bind' => array(
                'key' => $key,
                'del' => DBEnums::DELSIGN_NO,
                'cateid' => $iCateID
            )
        );
        $res = SelectDic::count( $where );
        
        if( $res && count( $res ) > 0 )
        {
            $objRet->status = 1; // 存在
            $objRet->msg = '关键字已存在，请更新关键字再保存..';
        }
        else
        {
            $objRet->status = 0; // 不存在
        }
        
        echo json_encode( $objRet );
    }
}
